import javax.swing.event.TableModelListener
import javax.swing.table.*
import javax.swing.*
import net.sshiffon.*
import net.miginfocom.swing.MigLayout
import	java.awt.*
import	java.awt.event.*
import	javax.swing.event.*


actions{
	action(id: "uploadAction",
			name: "Upload",
			mnemonic: "U",
			enabled: bind {model.anySelected},
		//	accelerator: shortcut("U"),
			closure: {
				fileList.selectedRows.each({controller.upload(it)})
            })
	action(id: "deleteAction",
			name: "Delete",
			//mnemonic: "D",
			enabled: bind {model.anySelected},
			//accelerator: shortcut("D"),
			closure: {
				fileList.selectedRows.each({controller.delete(it)})
				//controller.refresh()
            })
    action(id: "mkdirAction",
    		name: "New Dir",
    		closure: {
				   def pane = optionPane(message:'New directory name')
				   def ans = pane.showInputDialog('Make directory','newfolder')
				   controller.mkdir(ans)
				})
    action(id: "refreshAction",
    		name: "Refresh",
    		closure: {
		controller.refresh()
				})    
	action(id: "folderChooserAction", name:'cd', 
			closure: {
                    def fc = fileChooser(dialogTitle:"Choose a folder",
                            currentDirectory: new java.io.File(model.currentFolder), fileSelectionMode : JFileChooser.DIRECTORIES_ONLY)
                    if(fc.showOpenDialog() == JFileChooser.APPROVE_OPTION) { //user cancelled
                        model.currentFolder = fc.selectedFile
                        controller.refresh()
                    }
                    })
    action(id: "upDirAction",
    		name: "Up",
    		closure: controller.upDir
    		)
}
    //mainPanel =
    panel(id:'mainPanel', layout: new MigLayout("fill"))
    {
        label('Local Files',font: mainPanel.font.deriveFont(16.0f), constraints: "north")
        separator()
    	toolBar(constraints: "north")
//        panel(constraints: "north", layout: new MigLayout("fill"))
        {
            button(action: upDirAction, icon: imageIcon('/crystal16/folder.png'))
            separator()
            button(action: refreshAction, icon: imageIcon('/crystal16/reload.png'))
            separator()
            button(mkdirAction,icon: imageIcon('/crystal16/folder_new.png'))
            separator()
            button(action: folderChooserAction, icon: imageIcon('/crystal16/folder_favorites.png'))
        }
        panel(constraints: "north", layout: new MigLayout("fill"))
        {
        	label( text: bind { model.currentFolder } ,id:'currentFolder', constraints:'wrap')
        }

        scrollPane(constraints: "grow") {
        table(id: 'fileList', constraints: 'grow', autoResizeMode: JTable.AUTO_RESIZE_ALL_COLUMNS, autoCreateColumnsFromModel: true) {
        	current.selectionModel.addListSelectionListener({ evt -> 
    	  	model.anySelected = !fileList.selectionModel.selectionEmpty } as ListSelectionListener);

            tableModel(list:model.folderContents)
            {
               filetypeCol= propertyColumn(headerValue:' ',maxWidth: 20, propertyName:'type',
                        cellRenderer: {table,value,selected,hasFocus,row,column -> label('',icon:imageIcon(value == 'D' ? '/crystal16/folder_yellow.png' : '/crystal16/file_doc.png')) } as TableCellRenderer)
               filenameCol= propertyColumn(headerValue:'Name', propertyName:'name', editable: false)
               filesizeCol= propertyColumn(headerValue:'Size', propertyName:'size' ,editable: false)
            }

        }.addMouseListener({ evt -> if(evt.getClickCount() == 2 && !evt.isConsumed() && evt.getID()==java.awt.event.MouseEvent.MOUSE_CLICKED) {
                        evt.consume();
                        logger.debug("double clicked local file ${fileList.selectedRow} ${model.folderContents.get(fileList.selectedRow)}")
                        controller.processEntry(model.folderContents.get(fileList.selectedRow))
                      } } as java.awt.event.MouseListener);
        }
        panel(constraints: "south")
        {
            button(uploadAction,icon: imageIcon('/crystal16/upload.png'))
            button(deleteAction,icon: imageIcon('/crystal16/delete.png'))
        }
    }
    mainPanel.add(fileList.getTableHeader(), "north");
    


loadFolder = {
    currentFolderName, folderContents ->

    DefaultTableCellRenderer r = new DefaultTableCellRenderer()
    r.setHorizontalAlignment(JLabel.RIGHT)
    r.setFont( java.awt.Font.decode("Monospaced-10") )

    fileList.model = tableModel(list:model.folderContents)
            {
                propertyColumn(headerValue:' ',maxWidth: 20, propertyName:'type',
                        cellRenderer: {table,value,selected,hasFocus,row,column -> label('',icon:imageIcon(value == 'D' ? '/crystal16/folder_yellow.png' : '/crystal16/file_doc.png')) } as javax.swing.table.TableCellRenderer)
                propertyColumn(headerValue:'Name', propertyName:'name', editable: false)
               // propertyColumn(headerValue:'Size', propertyName:'size' ,editable: false)
                closureColumn(
                  cellRenderer: r,
                  header:'Size',
                  read: {row -> return row.type=='D' ? "" : net.sshiffon.FileSizeUtil.format(row.size, 2) }
                  )
                closureColumn(
                  header:'Modified',
                  read: {row -> return row.modified }
                  )
            }
}
def popupMenu=  popupMenu()
{
	menuItem( uploadAction )
	separator()
	menuItem( refreshAction )
	menuItem( mkdirAction )
	separator()
	menuItem( deleteAction )
}
fileList.addMouseListener({ e -> if (e.isPopupTrigger()) { popupMenu.show(e.getComponent(), e.getX(), e.getY());} } as java.awt.event.MouseAdapter)

